import React, { useState } from 'react'
import { Send, Upload, Plus, Trash2 } from 'lucide-react'
import TopicSelector from '../kafka/TopicSelector'
import { ProducerMessage } from '../../pages/MessageProducer'

interface BatchMessageFormProps {
  topics: string[]
  selectedTopic: string
  partitions: number[]
  partitionsLoading: boolean
  onTopicChange: (topic: string | null) => void
  onBatchProduce: (messages: ProducerMessage[]) => void
  isProducing: boolean
}

export function BatchMessageForm({
  topics,
  selectedTopic,
  partitions,
  partitionsLoading,
  onTopicChange,
  onBatchProduce,
  isProducing
}: BatchMessageFormProps) {
  const [messages, setMessages] = useState<ProducerMessage[]>([
    { key: '', value: '', format: 'json' }
  ])
  const [jsonInput, setJsonInput] = useState('')
  const [inputMode, setInputMode] = useState<'form' | 'json'>('form')

  const addMessage = () => {
    setMessages(prev => [...prev, { key: '', value: '', format: 'json' }])
  }

  const removeMessage = (index: number) => {
    if (messages.length > 1) {
      setMessages(prev => prev.filter((_, i) => i !== index))
    }
  }

  const updateMessage = (index: number, field: keyof ProducerMessage, value: any) => {
    setMessages(prev => prev.map((msg, i) => 
      i === index ? { ...msg, [field]: value } : msg
    ))
  }

  const handleJsonImport = () => {
    try {
      const parsed = JSON.parse(jsonInput)
      if (Array.isArray(parsed)) {
        // 将JSON对象数组转换为消息格式
        setMessages(parsed.map((item, index) => ({
          key: item.key || item.id?.toString() || `msg-${index}`,
          value: typeof item === 'object' ? JSON.stringify(item) : String(item),
          headers: item.headers || {},
          partition: item.partition,
          format: 'json'
        })))
        setInputMode('form')
        setJsonInput('')
        alert(`成功导入 ${parsed.length} 条消息`)
      } else {
        alert('JSON必须是数组格式，例如：[{"key": "key1", "value": "value1"}, ...]')
      }
    } catch (error) {
      console.error('JSON解析错误:', error)
      alert(`JSON格式错误: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!selectedTopic) {
      alert('请先选择Topic')
      return
    }

    const validMessages = messages.filter(msg => msg.value.trim())
    if (validMessages.length === 0) {
      alert('请至少输入一条有效消息')
      return
    }

    onBatchProduce(validMessages)
  }

  const handleReset = () => {
    setMessages([{ key: '', value: '' }])
    setJsonInput('')
  }

  return (
    <div className="card hover-lift">
      <div className="card-header">
        <h2 className="card-title">批量发送消息</h2>
        <p className="card-description">一次发送多条消息到Topic</p>
      </div>
      <div className="card-content">
        {/* Topic选择 */}
        <div className="mb-6">
          <TopicSelector
            topics={topics}
            selectedTopic={selectedTopic}
            onTopicChange={onTopicChange}
          />
        </div>

        {/* 输入模式切换 */}
        <div className="flex space-x-3 mb-6">
          <button
            type="button"
            onClick={() => setInputMode('form')}
            className={`btn ${inputMode === 'form' ? 'btn-primary' : 'btn-outline'}`}
          >
            表单输入
          </button>
          <button
            type="button"
            onClick={() => setInputMode('json')}
            className={`btn ${inputMode === 'json' ? 'btn-primary' : 'btn-outline'}`}
          >
            JSON导入
          </button>
        </div>

        {inputMode === 'json' ? (
          /* JSON输入模式 */
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                JSON消息数组
              </label>
              <textarea
                value={jsonInput}
                onChange={(e) => setJsonInput(e.target.value)}
                placeholder={`支持多种格式：
1. 标准消息格式：
[
  {"key": "key1", "value": "message1"},
  {"key": "key2", "value": "message2"}
]

2. 对象数组（自动转换为JSON字符串）：
[
  {"id": 1, "name": "张三", "age": 30},
  {"id": 2, "name": "李四", "age": 25}
]

3. 带分区和头信息：
[
  {
    "key": "user1",
    "value": "data1",
    "partition": 0,
    "headers": {"type": "user"}
  }
]`}
                rows={20}
                className="input w-full font-mono text-sm min-h-[500px]"
              />
              <p className="text-xs text-gray-500 mt-1">
                • 对象数组会自动转换为JSON字符串作为消息内容<br/>
                • 如果没有key字段，会使用id或自动生成<br/>
                • 支持partition和headers字段
              </p>
            </div>
            <div className="flex gap-3">
              <button
                type="button"
                onClick={handleJsonImport}
                className="btn-primary hover-lift"
              >
                <Upload className="w-4 h-4 mr-2" />
                导入消息
              </button>
              <button
                type="button"
                onClick={() => setInputMode('form')}
                className="btn-outline hover-lift"
              >
                返回表单
              </button>
            </div>
          </div>
        ) : (
          /* 表单输入模式 */
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="space-y-4">
              {messages.map((message, index) => (
                <div key={index} className="border rounded-lg p-4 bg-gray-50">
                  <div className="flex justify-between items-center mb-3">
                    <h4 className="text-sm font-semibold text-gray-700">
                      消息 #{index + 1}
                    </h4>
                    {messages.length > 1 && (
                      <button
                        type="button"
                        onClick={() => removeMessage(index)}
                        className="text-red-500 hover:text-red-700"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    )}
                  </div>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-medium text-gray-600 mb-1">
                        Key (可选)
                      </label>
                      <input
                        type="text"
                        value={message.key}
                        onChange={(e) => updateMessage(index, 'key', e.target.value)}
                        placeholder="消息Key"
                        className="input w-full text-sm bg-white"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-600 mb-1">
                        分区 (可选)
                      </label>
                      <input
                        type="number"
                        value={message.partition ?? ''}
                        onChange={(e) => updateMessage(index, 'partition', 
                          e.target.value ? Number(e.target.value) : undefined
                        )}
                        placeholder="分区号"
                        min="0"
                        className="input w-full text-sm bg-white"
                      />
                    </div>
                  </div>
                  
                  <div className="mt-3">
                    <label className="block text-xs font-medium text-gray-600 mb-1">
                      消息内容 *
                    </label>
                    <textarea
                      value={message.value}
                      onChange={(e) => updateMessage(index, 'value', e.target.value)}
                      placeholder="输入消息内容..."
                      rows={3}
                      className="input w-full text-sm bg-white resize-none"
                    />
                  </div>
                </div>
              ))}
            </div>

            <div className="flex justify-center">
              <button
                type="button"
                onClick={addMessage}
                className="btn-outline hover-lift"
              >
                <Plus className="w-4 h-4 mr-2" />
                添加消息
              </button>
            </div>

            {/* 操作按钮 */}
            <div className="flex flex-col sm:flex-row gap-3 pt-4">
              <button
                type="submit"
                disabled={!selectedTopic || isProducing || messages.every(m => !m.value.trim())}
                className="btn-primary hover-lift flex-1"
              >
                <Send className={`w-4 h-4 mr-2 ${isProducing ? 'animate-pulse' : ''}`} />
                {isProducing ? '发送中...' : `批量发送 (${messages.filter(m => m.value.trim()).length} 条)`}
              </button>
              <button
                type="button"
                onClick={handleReset}
                disabled={isProducing}
                className="btn-outline hover-lift"
              >
                重置表单
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  )
}
